﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using ERP_RORZE_SYSTEM;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERP_RORZE_DLL.Business
{
    public partial class panel_PODetails : UserControl
    {
        public panel_PODetails()
        {
            InitializeComponent();
            mySetting = new INISettings();
            myConnection = new SqlConnection(mySetting.SQLConnectionString);
            LoadData();
            this.PODetails.PopupMenuShowing += PODetails_PopupMenuShowing;
            this.poDetailcontextMenu.ItemClicked += poDetailcontextMenu_ItemClicked;

            this.PODetails.DoubleClick += PODetails_DoubleClick;
        }

        void PODetails_DoubleClick(object sender, EventArgs e)
        {
            callEditForm();
        }

        // Call Edit Form
        private void callEditForm()
        {
            DataRow row = this.PODetails.GetFocusedDataRow();
            if ((bool)row["Finished"])
            {
                MessageBox.Show("This Order has been finished");
            }
            else
            {
                frm_Edit_PODetails edit_form = new frm_Edit_PODetails();
                edit_form.poid = row["POID"].ToString();
                edit_form.order = row["OrderNo"].ToString();
                if (edit_form.LoadData())
                {
                    edit_form.ShowDialog();
                    //LoadData();
                }
                else
                {
                    MessageBox.Show("Cannot edit selected record. Please try again");
                }
            }
        }

        void poDetailcontextMenu_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            this.poDetailcontextMenu.Hide();            
            switch (e.ClickedItem.Name)
            {
                case "editSelection":
                    callEditForm();
                    break;
                case "cancelSelection":
                    callCancelFunction();
                    break;
                case "addSelection":
                    frm_Add_PODetails add_Form = new frm_Add_PODetails();
                    add_Form.ShowDialog();
                    //LoadData();
                    break;
                case "refreshSelection":
                    LoadData();
                    break;
            }
        }

        //////////////////////////
        /// Call Cancel Function
        ///////////////////////////
        private void callCancelFunction()
        {
            DataRow row = this.PODetails.GetFocusedDataRow();
            cancelOrderPODetails(row["OrderNo"].ToString(), row["POID"].ToString());
            //LoadData();
        }

        void PODetails_PopupMenuShowing(object sender, DevExpress.XtraGrid.Views.Grid.PopupMenuShowingEventArgs e)
        {
            this.poDetailcontextMenu.Show(MousePosition);            
        }       

        private void buttonAdd_Click(object sender, EventArgs e)
        {
            frm_Add_PODetails add_Form = new frm_Add_PODetails();
            add_Form.ShowDialog();
            //LoadData();
        }

        
        /////////////////////////////////
        /// Load POdetails into gridview
        /////////////////////////////////
        private void LoadData()
        {            
            DataSet sourceDataSet = new DataSet();
            SQLManagement mySQLManagement = new SQLManagement();
            mySQLManagement.SQLConnectionString = mySetting.SQLConnectionString;
            string sql = "SELECT t1.POID, t4.SupplierName, t1.OrderNo, t1.PartNo, t1.Quantity, t2.BuyingUnit,"
                + " t1.UnitPrice, t1.CurrencyID, t1.DeliveryDate, t6.TransportName, t5.DeliveryTermName,"
                + " t7.UnitID AS IQUnit, t2.[Buying/IQEx], t1.Purpose, t2.Remark AS Note, t1.Change, t1.Finished, t1.Cancelled"
                + " FROM [241_PODetails] AS t1"
                + " LEFT JOIN [222_Part] AS t2 ON t1.PartNo = t2.PartNo COLLATE Vietnamese_CI_AS"
                + " LEFT JOIN [241_PO] AS t3 ON t1.POID = t3.ID"
                + " LEFT JOIN [222_Supplier] AS t4 ON t3.SupplierID = t4.SupplierID"
                + " LEFT JOIN [222_DeliveryTerm] AS t5 ON t1.DeliveryTermID=t5.DeliveryTermID"
                + " LEFT JOIN [222_Transport] AS t6 ON t1.TransportID=t6.TransportID"
                + " LEFT JOIN [222_IQ] AS t7 ON t2.IQID = t7.IQID"
                + " WHERE t1.Change=0 AND t1.Finished=0 AND t1.Cancelled=0"
                + " ORDER BY SUBSTRING(t1.POID,5,6) DESC";
            sourceDataSet = mySQLManagement.SQL_Query(sql);
            if (sourceDataSet != null)
            {
                gridPODetails.DataSource = sourceDataSet.Tables[0];
            }
            else
            {
                DataTable newTable = new DataTable();
                newTable.Columns.Add("PO ID", typeof(string));
                newTable.Columns.Add("SupplierName", typeof(string));
                newTable.Columns.Add("OrderNo", typeof(string));
                newTable.Columns.Add("PartNo", typeof(string));
                newTable.Columns.Add("Quantity", typeof(int));
                newTable.Columns.Add("BuyingUnit", typeof(string));
                newTable.Columns.Add("UnitPrice", typeof(float));
                newTable.Columns.Add("Currency", typeof(string));
                newTable.Columns.Add("DeliveryDate", typeof(DateTime));
                newTable.Columns.Add("Transport", typeof(string));
                newTable.Columns.Add("DeliveryTerm", typeof(string));
                newTable.Columns.Add("IQUnit", typeof(string));
                newTable.Columns.Add("Buying/IQEx", typeof(int));
                newTable.Columns.Add("Purpose", typeof(string));
                newTable.Columns.Add("Note", typeof(string));
                newTable.Columns.Add("Change", typeof(bool));
                newTable.Columns.Add("Finished", typeof(bool));
                newTable.Columns.Add("Cancelled", typeof(bool));
                gridPODetails.DataSource = newTable;
            }
            PODetails.Columns[0].Caption = "PO ID";
            PODetails.Columns[1].Caption = "Supplier Name";
            PODetails.Columns[2].Caption = "Order No";
            PODetails.Columns[3].Caption = "Part No";
            PODetails.Columns[4].Caption = "Quantity";
            PODetails.Columns[5].Caption = "Buying Unit";
            PODetails.Columns[6].Caption = "Unit Price";
            PODetails.Columns[7].Caption = "Currency";
            PODetails.Columns[8].Caption = "Delivery Date";
            PODetails.Columns[9].Caption = "Transpor";
            PODetails.Columns[10].Caption = "Delivery Term";
            PODetails.Columns[11].Caption = "IQUnit";
            PODetails.Columns[12].Caption = "Buying/IQ Exchange";
            PODetails.Columns[13].Caption = "Purpose";
            PODetails.Columns[14].Caption = "Note";
            PODetails.Columns[15].Caption = "Change";
            PODetails.Columns[16].Caption = "Finished";
            PODetails.Columns[17].Caption = "Cancelled";
            PODetails.BestFitColumns();
        }

        /////////////////////////////////////////////////////
        /// Cancel OrderNo in PODetails
        /////////////////////////////////////////////////////
        private void cancelOrderPODetails(string orderno, string poid)
        {
            if (MessageBox.Show("Really cancel?", "Confirm cancel", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                bool isFinished = checkPODetailsFinished(orderno, poid);
                if (isFinished)
                {
                    MessageBox.Show("Cannot cancel. The OrderNo " + orderno + " of POID " + poid + " has been finished.");
                }
                else
                {
                    int receiveQuantity = sumPartReceiveQuantity(orderno, poid);
                    if (receiveQuantity > 0)
                    {
                        MessageBox.Show("Cannot cencel. There are " + receiveQuantity + " received units for the OrderNo " + orderno);
                    }
                    else
                    {
                        try
                        {
                            myConnection.Open();
                            SqlCommand cmd_sql = myConnection.CreateCommand();
                            cmd_sql.CommandText = "UPDATE [241_PODetails] SET Cancelled=1, Finished=1"
                                + " WHERE OrderNo='" + orderno + "' AND POID='" + poid + "' AND Finished=0";
                            cmd_sql.ExecuteNonQuery();                            
                            cmd_sql.Dispose();
                            myConnection.Close();
                            MessageBox.Show("The OrderNo " + orderno + " of POID " + poid + " has been canceled successfully.");

                            if (checkAllOrderNoCancelled(poid))
                            {
                                if (MessageBox.Show("All OrderNo of POID " + poid + " has been cancelled. Do you want to cancel POID " + poid + " ?", "Cancel POID", MessageBoxButtons.YesNo) == DialogResult.Yes)
                                {
                                    cancelPO(poid);
                                }
                            }
                        }
                        catch
                        {
                            if (myConnection.State == ConnectionState.Open)
                            {
                                myConnection.Close();
                            }
                            MessageBox.Show("Cannot cancel the OrderNo " + orderno + " of POID " + poid + ". Please try again.");
                        }
                    }
                }
            }
        }

        //////////////////////////////////////////////
        /// Check Finished for OrderNo and POID
        //////////////////////////////////////////////
        private bool checkPODetailsFinished(string orderno, string poid)
        {
            bool ret = false;
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT COUNT(OrderNo) FROM [241_PODetails]"
                    + " WHERE OrderNo='" + orderno + "' AND POID='" + poid + "' AND Finished=1";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                if (dataReader.Read())
                {
                    int numberRecord = Int32.Parse(dataReader[0].ToString());
                    if (numberRecord > 0)
                    {
                        ret = true;
                    }
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show("Cannot get check finished for OrderNo " + orderno);
            }
            return ret;
        }

        ////////////////////////////////////////////////////////
        /// Sum quantity of Part Receive for OrderNo and POID
        ///////////////////////////////////////////////////////
        private int sumPartReceiveQuantity(string orderno, string poid)
        {
            int ret = 0;
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT SUM(Quantity) FROM [241_PartReceive] WHERE OrderNo='" + orderno + "' AND POID='" + poid + "'";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                if (dataReader.Read())
                {
                    if (!string.IsNullOrEmpty(dataReader[0].ToString()))
                    {
                        ret = Int32.Parse(dataReader[0].ToString());
                    }
                }                
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show("Cannot get sum quantity of PartReceive");
            }
            return ret;
        }

        /////////////////////////////////////////////////////
        /// Check if all OrderNo for POID has been cancelled 
        /////////////////////////////////////////////////////
        private bool checkAllOrderNoCancelled(string poid)
        {
            bool ret = true;
            myConnection.Open();
            SqlCommand cmd_sql = myConnection.CreateCommand();
            cmd_sql.CommandText = "SELECT COUNT(OrderNo) FROM [241_PODetails]"
                + " WHERE POID='" + poid + "' AND Cancelled=0";
            SqlDataReader dataReader = cmd_sql.ExecuteReader();
            if (dataReader.Read())
            {
                int numberRecord = Int32.Parse(dataReader[0].ToString());
                if (numberRecord > 0)
                {
                    ret = false;
                }
            }
            dataReader.Close();
            cmd_sql.Dispose();
            myConnection.Close();
            return ret;
        }

        ///////////////////////////////////////////////////
        /// Cancel POID
        ///////////////////////////////////////////////////
        private void cancelPO(string poid)
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "UPDATE [241_PO] SET Cancelled=1, Finished=1"
                    + " WHERE ID='" + poid + "' AND Finished=0";
                cmd_sql.ExecuteNonQuery();
                cmd_sql.Dispose();
                myConnection.Close();
                MessageBox.Show("The POID " + poid + " has been canceled successfully.");
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show("Cannot cancel the POID " + poid + ". Please try again.");
            }
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            callCancelFunction();
        }

        private void buttonEdit_Click(object sender, EventArgs e)
        {
            callEditForm();
        }

        private void buttonRefresh_Click(object sender, EventArgs e)
        {
            LoadData();
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            frm_Import_PODetails import_form = new frm_Import_PODetails();
            import_form.ShowDialog();
            //LoadData();
        }
    }
}
